package com.penghaonan.appframework.utils.monitor;

import com.penghaonan.appframework.utils.WeakObservableList;

public abstract class AMonitor<T> implements IMonitor<T> {
    protected final WeakObservableList<MonitorListener<T>> listeners = new WeakObservableList<>();

    @Override
    public void addListener(MonitorListener<T> listener) {
        boolean added = listeners.addListener(listener);
        if (added) {
            listener.onStatusChanged(AMonitor.this, getValue());
        }
    }

    @Override
    public void removeListener(MonitorListener<T> listener) {
        listeners.removeListener(listener);
    }

    @Override
    public void release() {
        listeners.clear();
    }

    protected void notifyListeners() {
        listeners.iterate(new WeakObservableList.OnIterator<MonitorListener<T>>() {
            @Override
            protected boolean onIterator(MonitorListener<T> item) {
                item.onStatusChanged(AMonitor.this, getValue());
                return false;
            }
        });
    }
}
